package touro.mancala.client;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import touro.mancala.client.view.BoardView;
import touro.mancala.client.view.StoreView;

public class MoveListener implements MouseListener {

	private MoveController controller;
	private GameState state = GameState.getGameState();

	public MoveListener() {
		controller = new MoveController();
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		
		StoreView view = (StoreView)e.getSource();
		BoardView boardView = (BoardView)view.getParent();
		if(state.getActivePlayer() instanceof AIPlayer)
		{
			boardView.setMessage("It is not your turn.  Please wait.");
		}
		else {
			view.repaint();
			String outputMessage;
			try {
				outputMessage = controller.move(view.getStore());
			} catch (Exception exc) {
				exc.printStackTrace();
				outputMessage = exc.getMessage();
			}

			boardView.setMessage(outputMessage);
			boardView.repaint();
			try {
				aiPlayerGoes();
			} catch (InterruptedException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			
		}
	}

	/**
	 * 
	 */
	private void aiPlayerGoes() throws Exception{
		Player p = state.getActivePlayer();
		if(p instanceof AIPlayer)
		{
			int nextMove = (((AIPlayer)p).getMove(state.getBoard()));
			controller.move(nextMove);
			if(state.getActivePlayer() instanceof AIPlayer)
			{
				aiPlayerGoes();//I know this is horrible structure
			}
		}	
	}
}
